import React, {useEffect, useState} from "react";
import {Dimensions, StyleSheet, Text, TextInput, TouchableHighlight, View} from "react-native";
import {fontSize_13, fontSize_14, fontSize_15} from "./theme";
import {CheckBox} from "react-native-elements";
import SimpleToast from "react-native-simple-toast";
import {getWalletByKeystore, getWalletByMnemonic, getWalletByPrivateKey} from "./smartxL2Libs/smartxL2Web3";
import {
    addWallet,
    getChainBaseByChainID, getChainInfo,
    getWalletInfo,
    updateNowWallet,
    useWalletType,
    walletInfoType
} from "./smartxL2Libs/L2_Data";

const {width,height,scale} = Dimensions.get("window");

const L2_ImportByKeystore = ({navigation,route}:any) => {
    const [importWay,setImportWay] = useState(route?.params?.importWay)
    const [providerUrl,setProviderUrl] = useState(route?.params?.providerUrl)
    const [chainID,setChainID] = useState(route?.params?.chainID)
    const [key,setKey] = useState("")
    const [password,setPassword] = useState("")
    const [read, setRead] = useState(false);

    useEffect(()=>{
        navigation.setOptions({
            title:"Keystore导入"
        })
    },[])
    const initNewWalletName = async (chainID:string) => {
        let net = await getChainBaseByChainID(chainID)
        if(!net)
        {
            return "";
        }
        let walletListNet = await getChainInfo(chainID);
        let name = net.coinName+"-"+(walletListNet.walletList.length+1).toString();
        return name;
    }
    const importWallet = async () => {
        if(!read)
        {
            SimpleToast.show("您尚未阅读并同意服务及隐私条款");
            return ;
        }
        if(password==="")
        {
            SimpleToast.show("请输入密码");
            return ;
        }
        if(key==="")
        {
            SimpleToast.show("请输入Keystore");
            return ;
        }
        let wallet = await getWalletByKeystore(key,password);
        console.log(wallet)
        if(!wallet)
        {
            SimpleToast.show("密码错误");
            return ;
        }
        let walletName = await initNewWalletName(chainID);
        let walletInfo: walletInfoType = {
            address: wallet.address,
            privateKey: wallet.privateKey,
            tip: "",
            walletName,
            password,
            chainID,
            mnemonic:"",
            balance:"0",
        };
        console.log(walletInfo)
        let addWalletRes = await addWallet(walletInfo)
        if (addWalletRes.success) {
            let nowWallet: useWalletType = {chainID, providerUrl: providerUrl, address: wallet.address};
            if (await updateNowWallet(nowWallet)) {
                navigation.navigate("L2_Tabs");
                return;
            }
            console.log('Error:updateNowWallet Error')
            return;
        }
        SimpleToast.show(addWalletRes.falseReason);

    }
    return (
        <View style={styles.container}>
            <Text style={styles.TipText}>直接复制粘贴 Keystore 文件内容至输入框。或者通过生产KeyStore 内容的二维码，扫描录入</Text>
            <TextInput
                placeholder={"Keystore 文本内容"}
                style={styles.keyInputContainer}
                multiline={true}
                onChangeText={value => setKey(value)}
            />
            <TextInput
                placeholder={"Keystore 密码"}
                onChangeText={value => setPassword(value.trim())}
                secureTextEntry={true}
                style={{
                    width:"100%",fontSize:fontSize_15,padding:0,
                    paddingTop:10,borderBottomWidth:5/scale,
                    borderBottomColor:"#f0f2f3", paddingBottom:10}}
            />
            <View
                style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent:"flex-start",
                    width:'100%',
                    height:50
                }}
            >
                <CheckBox
                    // checkedIcon='dot-circle-o'
                    // uncheckedIcon='circle-o'
                    size={18}
                    checked={read}
                    onPress={() => setRead(!read)}
                    containerStyle={{ margin: 0, padding: 0,marginLeft:0 }}
                    checkedColor='#2980fe'
                />
                <Text style={{fontSize:fontSize_15}}>我已阅读并同意</Text>
                <Text
                    onPress={() => {}}
                    style={{ paddingLeft: 4, color: '#2a81fe',fontSize:fontSize_15 }}
                >《服务及隐私条款》</Text>
            </View>
            <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                importWallet();
            }}>
                <View style={styles.importBTN}>
                    <Text style={{fontSize:fontSize_15,color:"white"}}>导入钱包</Text>
                </View>
            </TouchableHighlight>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: "white"
    },
    TipText:{
        width:"100%",
        fontSize:fontSize_14,
        color:"#7b7b7b",
        flexWrap:"wrap",
        marginTop:20,
        lineHeight:18,
    },
    keyInputContainer:{
        width:"100%",
        height:120,
        fontSize:fontSize_14,
        lineHeight:50,
        borderWidth:1/scale,
        borderColor: '#BFBFBFFF',
        borderRadius: 6,
        backgroundColor: '#F8FAFCFF',
        textAlignVertical:"top",
        textAlign:"left",
        padding:5,
        marginTop:10,
        marginBottom:10,
        flexWrap:"wrap",
    },
    importBTN:{
        marginTop:20,
        marginBottom:20,
        width:width-20,
        borderRadius:5,
        height:40,
        backgroundColor:"#2980fe",
        alignItems:"center",
        justifyContent:"center"
    }
})
export default L2_ImportByKeystore;


